package com.mspbots.attendance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mspbots.attendance.mapper.TenantAttendanceApproveMapper;
import com.mspbots.attendance.model.TenantAttendanceApprove;
import com.mspbots.attendance.service.TenantAttendanceApproveService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author aff
 */
@Log4j2
@Service
public class TenantAttendanceApproveServiceImpl extends ServiceImpl<TenantAttendanceApproveMapper, TenantAttendanceApprove>
        implements TenantAttendanceApproveService {
    @Override
    public Object saveApprove(TenantAttendanceApprove tenantAttendanceApprove) {
        tenantAttendanceApprove.setUpdateTime(LocalDateTime.now());
        tenantAttendanceApprove.setStatus("Pending approve");
        tenantAttendanceApprove.setManagerUserId(this.baseMapper.selectManagerById(tenantAttendanceApprove));
        Map<String, Object> map = new HashMap<>();
        map.put("tenant_attendance_id", tenantAttendanceApprove.getTenantAttendanceId());
        List<TenantAttendanceApprove> result = this.baseMapper.selectByMap(map);
        Boolean flag;
        if (ObjectUtils.isEmpty(result)) {
            flag = this.save(tenantAttendanceApprove);
        } else {
            TenantAttendanceApprove taa = result.get(0);
            tenantAttendanceApprove.setId(taa.getId());
            flag = this.updateById(tenantAttendanceApprove);
        }
        return flag;
    }

    @Override
    public Object updateApprove(TenantAttendanceApprove tenantAttendanceApprove) {
        Boolean result = false;
        tenantAttendanceApprove.setApproveTime(LocalDateTime.now());
        TenantAttendanceApprove current = this.baseMapper.selectById(tenantAttendanceApprove.getId());
        if (ObjectUtils.isEmpty(current)) {
            return result;
        }
        tenantAttendanceApprove.setLogTimeUpdated(current.getLogTimeUpdated());
        tenantAttendanceApprove.setTenantAttendanceId(current.getTenantAttendanceId());
        Integer approveLog = 0;

        Integer approveFlag = this.baseMapper.updateApprove(tenantAttendanceApprove);
//        if(tenantAttendanceApprove.getStatus().toLowerCase().equals("approved")){
//            approveLog = this.baseMapper.updateAttendanceLog(tenantAttendanceApprove);
//            result =  approveFlag > 0 && approveLog > 0;
//        }else{
//            result =  approveFlag > 0;
//        }
        result = approveFlag > 0;
        return result;
    }
}
